<?
ini_set("display_errors",1);
include($_SERVER['DOCUMENT_ROOT'].'/includes/functions.inc.php');
include($_SERVER['DOCUMENT_ROOT'].'/portals/config.php');
include($_SERVER['DOCUMENT_ROOT'].'/groups/database.php');

init_session();

if (empty($_SESSION['user_id'])) {
	include($_SERVER['DOCUMENT_ROOT'].'/portals/login.inc.php');
	exit;
}



include($_SERVER['DOCUMENT_ROOT'].'/portals/header.inc.php');



$id = intval(@$_GET['id']);



if ($id) {
	$current = getRow("SELECT * FROM portal WHERE portal_id = $id");
	
	if ($current['status_id'] != 1 || $current['user_id'] != $_SESSION['user_id']) {
		die("unable to edit this Portal");
	}
	print "<h3>Edit Current Portal</h3>";
} else {
	print "<h3>Add New Portal</h3>";
}

if (!empty($_POST)) {

	$updates = array();
	
	$data = getAssoc("SHOW FULL COLUMNS FROM portal");
	
	foreach ($data as $key => $row) {
		if (!empty($row['Comment']) && (preg_match('/^\+/',$row['Comment']) xor empty($_GET['adv']))) {
			if ($key == 'tags') {
				//tags handled seperately below (have to be after insertion so know portal_id) 
				
			} elseif ($row['Type'] == "enum('N','Y')") {//special case - its a tickbox
				$updates[$key] = empty($_POST[$key])?'N':'Y';
			
			} elseif (preg_match("/^(set|enum)\(([^)]*)\)/",$row['Type'],$m)) {
				$values = explode(',',$m[2]);

				if (!empty($_POST[$key])) {
					if (is_array($_POST[$key])) {
						$updates[$key] = str_replace("'",' ',implode(',',$_POST[$key]));
					} else {
						$updates[$key] = str_replace("'",' ',$_POST[$key]);
					}
				}
			
			} elseif (empty($value) && !empty($_POST[$key.'_Other']) && preg_match('/^(\w+)_id/',$key,$m2)) {
				
				$n1 = $m2[1];
				
				$u = array();
				$u['name'] = $_POST[$key.'_Other'];
				$sql= updates_to_insert($n1,$u);
				queryExecute($sql);
				if ($new_id = mysql_insert_id()) {
				
				
					$updates[$key] = $new_id;	
				} else {
					//if it failed it must be a duplicate?
					
					$updates[$key] = getOne("SELECT `$key` FROM `$n1` WHERE name = '".mysql_real_escape_string($u['name'])."'");
				}
			} else {
				$updates[$key] = trim($_POST[$key]);
				
				//TODO add validation - in paricular the url's
			
			}
			
			if ($id && $updates[$key] == $current[$key]) {
				unset($updates[$key]);
			}
			
		}
	}
	
	//tags precheck
	if (!empty($_POST['tag_id'])) {
		$found = 0;
		if ($id) {
			$tags = getAssoc("SELECT tag.* FROM tag INNER JOIN portal2tag USING (tag_id) WHERE portal_id = $id ORDER BY portal2tag.created");
			if ($tags) {
				foreach ($tags as $tid => $row2) {
					if (in_array($tid,$_POST['tag_id'])) {
						$found++;
					}
				}
			}
		} 
		if (count($_POST['tag_id']) != $found) {
			$tagsDontMatch = 1;
		}
		
	}
	
	if (!empty($updates) || !empty($tagsDontMatch)) {
		
		$user_id = $_SESSION['user_id']?$_SESSION['user_id']:1;
		
		if (!empty($updates)) {
			
			if ($id) {
				if (isset($updates['linear_start_id'])) {
					$updates['last_sorted'] = 0;
				}
				$sql= updates_to_update('portal',$updates,'portal_id',$id);
				
			} else {
				$updates['user_id'] = $user_id;
				$updates['created'] = 'NOW()';
				$sql= updates_to_insert('portal',$updates);

			}

			queryExecute($sql);
			
			if (!$id) {
				$id = mysql_insert_id();
				
				//TODO - this is the basic setup - shoudlnt really be hardcoded!
				$table = "p2.gridimage{$id}_bi";
				$sql = "CREATE TABLE $table LIKE gridimage";
				queryExecute($sql);
				
				$table = "p2.gridimage2tag{$id}_bi";
				$sql = "CREATE TABLE $table LIKE gridimage2tag";
				queryExecute($sql);
				
				if (!empty($_POST['q']) && preg_match('/^http:\/\/www.geograph.org.uk\//',$_POST['q'])) {
					$sql = "INSERT INTO `filter` VALUES (NULL, $id, 1, 0, 'any', 'gurl', 'In this Collection', ".dbQuote($_POST['q']).", 0, NOW(), NOW())";
					queryExecute($sql);
				} elseif (!empty($_POST['q'])) {
					$sql = "INSERT INTO `filter` VALUES (NULL, $id, 1, 0, 'any', 'sphinx', 'Full Text Query', ".dbQuote($_POST['q']).", 0, NOW(), NOW())";
					queryExecute($sql);
				} else {
					//placeholders - so there is at least something to get going?
					$sql = "INSERT INTO `filter` VALUES (NULL, $id, 1, 0, 'any', 'sphinx', 'Full Text Query', '', 0, NOW(), NOW()),
					(NULL, $id, 1, 0, 'any', 'gurl', 'In this Collection', '', 0, NOW(), NOW())";
					queryExecute($sql);
				}
				
				$sql = "CREATE VIEW p2.`gridimage{$id}_bi_view` AS SELECT * 
				FROM p2.`gridimage{$id}_bi` 
				INNER JOIN geograph_live.gridimage_search AS gs
				USING ( gridimage_id ) 
				WHERE status_id = 1";
				queryExecute($sql);
				
				$sql = "CREATE VIEW p2.`gridimage_tag{$id}_bi_view` AS SELECT tag.*, gridimage_id, gi.created as gi_created
				FROM p2.`gridimage2tag{$id}_bi` gi
				INNER JOIN tag
				USING ( tag_id ) 
				WHERE status_id = 1";
				queryExecute($sql);
				
			}
		}
		
		if ($tagsDontMatch && !empty($_POST['tag_id'])) {
			
			//$tags array set by the precheck :)
		
			if (!empty($tags)) {//see if any need deleting
				$found = 0 ;
				foreach ($tags as $tid => $row2) {
					if (in_array($tid,$_POST['tag_id'])) {
						$found++;
					} else {
						$sql = "DELETE FROM portal2tag WHERE portal_id = $id AND tag_id = $tid";
						queryExecute($sql);
						
						//log the portal2tag
						$u = array();
						$u['table'] = 'portal2tag';
						$u['table_id'] = $id;
						$u['name'] = 'tag_id';
						$u['value'] = '-'.$tid;
						$u['user_id'] = $user_id;
						$sql= updates_to_insert('update_log',$u);
						queryExecute($sql);
					}
				}
			}
		
			foreach ($_POST['tag_id'] as $idx => $text) {
				if ($text == '-deleted-') {
					//its either a tag created and deleted (so we can ignore) or its been deleted above!
				} elseif (isset($tags[$text])) {
					//its matches - nothing to do 
				} else {
					//its a new tag for this portal!
					
					if (is_numeric($text)) {
						$tag_id = $text;
					} else {
						$tag_id = getOne("SELECT tag_id FROM `tag` WHERE `display` = ".dbQuote($text));
					}
					
					if (empty($tag_id)) {
						//need to create it!
						
						$u = array();
						$u['tag'] = str_replace(' ','-',trim(preg_replace('/[^\w :\-]+/','',strtolower($text)))); //TODO - make unique?
						$u['display'] = $text;
						$u['added_by'] = $user_id;
						$u['created'] = 'NOW()';
						$bits = explode(':',$u['tag']);
						if (count($bits) > 1) {
							$u['prefix'] = $bits[0];
						}
						$sql= updates_to_insert('tag',$u);
						queryExecute($sql);
						
						$tag_id = mysql_insert_id();

						//log the tag
						$u = array();
						$u['table'] = 'tag';
						$u['table_id'] = $tag_id;
						$u['name'] = 'display'; //no point logging all the values? just the display should be enough. 
						$u['value'] = $text;
						$u['user_id'] = $user_id;
						$sql= updates_to_insert('update_log',$u);
						queryExecute($sql);
					}
					
					
					$u = array();

					$u['portal_id'] = $id;
					$u['tag_id'] = $tag_id;
					$u['added_by'] = $user_id;
					
					$sql= updates_to_insert('portal2tag',$u);
					queryExecute($sql);
				
					//log the portal2tag
					$u = array();
					$u['table'] = 'portal2tag';
					$u['table_id'] = $id;
					$u['name'] = 'tag_id';
					$u['value'] = $tag_id;
					$u['user_id'] = $user_id;
					$sql= updates_to_insert('update_log',$u);
					queryExecute($sql);
				}
			}
		
		
		}
		
		
		
		print "<p>Updates Saved. Thank you</p>";

		print "<p><a href=\"portal.php?id=$id\">View Portal Page</a></p>";
		
		if (empty($_GET['id'])) {
			print "<p><b><a href=\"filters.php?id=$id\">View Filters Page</a></b></p>";
		}
		
?>
<form name="redirect">
<p>You will be automatically redirected in <input type="text" size="3" name="seconds"> seconds.</p>
</form>
<script>
var destiniation="<? echo (empty($_GET['id']))?'filters':'portal'; ?>.php?id=<? echo $id; ?>";
var start=5;
var current=document.forms['redirect'].seconds.value=start+1
function redirectTick() {
	if (current==1) {
		window.location=destiniation;
		return;
	} else{
		current-=1;
		document.forms['redirect'].seconds.value=current;
		setTimeout("redirectTick()",1000);
	}	
}
redirectTick();
</script>
<?

		//log the updates
		foreach ($updates as $key => $value) {
			if (!is_null($value)) {
				$u = array();
				$u['table'] = 'portal';
				$u['table_id'] = $id;
				$u['name'] = $key;
				$u['value'] = $value;
				$u['user_id'] = $user_id;
				$sql= updates_to_insert('update_log',$u);
				queryExecute($sql);
			}
		}
		
		exit;
	}

}



if ($id) {
	print "<p>Editing Portal: <b>".he($current['title'])."</b>. <a href=\"portal.php?id=$id\">Return to listing</a> (without saving changes)</p>";
} else {
	print "<p><small>&middot; A portal is a mini website, show casing a selection of Geograph images. Use this screen to create a new portal, in the next step define what images are included in your portal by means of 'filters'. These filters allow you to select a subset of the whole geograph archive to create your portal along a specific theme.</small></p>";
}

?>

<form method="post">

<? if (empty($_GET['adv'])) { ?>
<p><b>Title and Domain is Required</b>, otherwise optional.<br/>The `Domain` is used for the link to the portal. <tt>http://<i>your-choice</i>.portal.geographs.org/</tt></p>
<? } else { ?>
<p>All values optional</p>
<? } ?>

<table class="edittable">
<?
	$data = getAll("SHOW FULL COLUMNS FROM portal");
	
	print "<input type=\"hidden\" name=\"id\" value=\"$id\"/>";
	
	foreach ($data as $idx => $row) {
	
		if (!empty($row['Comment']) && (preg_match('/^\+/',$row['Comment']) xor empty($_GET['adv']))) {
			
			$name = $row['Field'];
			$value = htmlentities($current[$name]);
			
			if ($name == 'tags') {
				print "<tr>";
				print "<th>Tags</th>";

				print "<td>";
				print "Current Tags: <span id=\"tags\">";
				if ($id) {
					$tags = getAll("SELECT tag.* FROM tag INNER JOIN portal2tag USING (tag_id) WHERE portal_id = $id ORDER BY portal2tag.created");
					
				} 
				
				if (!empty($tags)) {
					foreach ($tags as $idx => $row2) {
						print "<span class=\"tag\" id=\"tag{$row2['tag_id']}\">";
						print "<input type=\"hidden\" name=\"tag_id[]\" id=\"tagi{$row2['tag_id']}\" value=\"{$row2['tag_id']}\"/>";
						print "<span>".he($row2['display'])."</span>";
						print "<a href=\"javascript:removeTag({$row2['tag_id']})\" class=\"delete\">X</a>";
						print "</span>&nbsp; ";
					}
				} else {
					print "<i>none</i>";
				}
				
				print "</span>";
				print "<br/>Add new Tag: ";
				print "<input type=\"text\" name=\"__newtag\" size=\"20\" maxlength=\"32\" onkeyup=\"if (this.value.length > 2) {loadTagSuggestions('q='+escape(this.value));}\"/>";
				
				print "<input type=\"button\" value=\"Add\" onclick=\"addTag(this.form.elements['__newtag'].value);this.form.elements['__newtag'].value='';this.form.elements['__newtag'].focus();\"/>";
				print " (click X to remove tag)";
				print "<div id=\"suggestions\"></dig>";
				print "</td>";
				print "</tr>";
			} else {
				print "<tr>";
				print "<th>".ucfirst(str_replace('_',' ',str_replace('_id','',$row['Field'])))."</th>";

				print "<td>";

				preg_match("/^(\w+)\(?([^)]*)\)?/",$row['Type'],$m);
				switch($m[1]) {
					case "enum": 
						if ($row['Type'] == "enum('N','Y')") {

							$checked = ($value == 'Y')?' checked="checked"':''; 
							print "<input type=\"checkbox\" name=\"$name\" $checked/>";
						} else {
							preg_match("/\('(.+)'\)/",$row['Type'],$m);
							$names = explode("','",$m[1]);
							print "<select name=\"$name\">";
							foreach ($names as $name) {
								$selected = ($value == $name)?' selected="selected"':''; 
								printf("<option%s>%s</option>",$selected,$name);
							}
							print "</select>";
						}
						break;
					case "set": 
						$values = explode(',',$m[2]);
						if (count($values) > 10) {
							print "TODO";
						} else {
							foreach ($values as $key=>$val) {
								$checked = preg_match('/(^|,)'.preg_quote(trim($val,"'"),'/').'(,|$)/',$value )?' checked="checked"':''; 
								$v = htmlentities(trim($val,"'"));
								print "<label for=\"{$name}_$v\" class=\"nowrap\"><input type=\"checkbox\" name=\"{$name}[]\" id=\"{$name}_$v\" value=\"$v\"$checked/> $v&nbsp;</label> ";
							}
						}
						break;
					case 'int': 
						print "<input type=\"text\" name=\"$name\" value=\"$value\" size=\"10\" maxlength=\"11\"/> (numeric)";
						break;
					case 'mediumint':
						if (preg_match('/^(\w+)_id/',$name,$m2)) {
							$n1 = $m2[1];
							if ($name == 'status_id') {
								print "<select name=\"$name\">";
							} elseif ($name == 'category_id') {
								print "<select name=\"$name\" onchange=\"setupOther(this);loadTagSuggestions('category_id='+this.options[this.selectedIndex].value)\">";
							} else {
								print "<select name=\"$name\" onchange=\"setupOther(this)\">";
							}
							$col = getAssoc($sql = "SELECT `$name`,name FROM `$n1` WHERE enabled = 'Y' ORDER BY sort_order,`$name`");
							#print_rp($sql);
							foreach ($col as $key=>$val) {
								printf("<option value=\"%s\"%s>%s</option>",$key,($key==$value)?' selected':'',htmlentities($val));
							}
							
							
							if ($name != 'status_id') {
								print "<option value=\"\">...Other (Create new)</option>";
								print "</select>";
								$maxlength=32;
								$size=min(40,$maxlength);
								print "<div id=\"{$name}_div\" style=\"display:none\">Other: <input type=\"text\" name=\"{$name}_Other\" size=\"$size\" value=\"\" maxlength=\"$maxlength\"/></div>"; 
							} else {
								print "</select>";
							}
							break;
						} else {
							//TODO fall though to below?
							//print "TODO";
						}
						
					case 'varchar': 
						$maxlength=intval($m[2]);
						$size=min(70,$maxlength);
						print "<input type=\"text\" name=\"$name\" size=\"$size\" value=\"$value\" maxlength=\"$maxlength\"";
						
						if ($name == 'domain') {
							print " onkeyup=\"checkDomain(this,$id)\" onfocus=\"initalPopulate(this,$id)\"/>";
							print "<span id=\"checkMsg\" style=color:red>.portal.geographs.org</span>";
						} else {
							print "/>";
						}
						break;
					case 'datetime':
						//TODO this currently ugly hack!
						$value = substr($value,0,10);
					case 'date': 
						print "<input type=\"text\" name=\"$name\" value=\"$value\" size=\"10\" maxlength=\"20\"/> YYYY-MM-DD";
						break;
					case 'text': 
						print "<textarea name=\"$name\" rows=\"5\" cols=\"60\">$value</textarea>";
						break;
					default:
						print $row['Type']; break;
				}
				

				print "<div class=\"helpinfo\">".preg_replace('/^\+/','',$row['Comment'])."</div>";
				print "</td>";
				print "</tr>";
			}
		}
		
	}
	
if (!$id) { ?>
<tr>
	<th>Quick Filter</th>
	<td>If you just want to populate your portal on <a href="http://www.geograph.org.uk/article/Word-Searching-on-Geograph" target="_blank">a "keywords" word search</a>, enter the keywords in this box.<br/>
	Alternativly enter the FULL page url of a collection (article, gallery, themed topic or shared description only)<br/>
	<input type="text" name="q" value="" size="60" maxlength="250"> <input type=button value=Test onclick="window.open('http://www.geograph.org.uk/search.php?searchtext='+encodeURI(this.form.elements['q'].value)+'&amp;do=1')"/> <input type="button" value="use title" onclick="this.form.elements['q'].value = this.form.elements['title'].value.toLowerCase()"><br/>
	This will be used to create the initial definition of the portal. Leave blank to proceed to the standard full filter setup screen.<br/>
	<i>Only includes images and pages from geograph.org.uk (Geograph Britain and Ireland) currently, support for other domains/projects comming soon... </i>
	</td>
</tr>
<? } if (empty($_GET['adv'])) { ?>
<tr>
	<td colspan="2" class="important">By clicking the button below, you agree to release your portal (and its definiton) under the <b class="nowrap">Creative Commons Attribution-Share Alike 3.0</b> Licence. <a title="View licence" href="http://creativecommons.org/licenses/by-sa/3.0/" target="_blank" class="nowrap">Here is the Commons Deed outlining the licence terms</a></td>
</tr>
<? } ?>
<tr>
	<th>&nbsp;</th>
	<td><input type="submit" name="save" value="Submit Changes" id="submitButton" <? if (!$id) { echo "disabled";} ?>/></td>
</tr>
</table>
</form>

<? if (empty($_GET['adv'])) { ?>
<p class=message>P.S. You define what images are shown in your portal in a seperate step.</p>
<? } ?>

<script>
function setupOther(that) {
	if (that.options[that.selectedIndex].text.indexOf('...Other') == 0) {
		show = true;
	} else {
		show = false;
	}
	
	document.getElementById(that.name+"_div").style.display=show?'':'none';
}

function addTag(text,suggestion) {
	
	if (!text || text.length == 0) {
		alert('No tag specified');
		return;
	}
	
	var div = document.getElementById('tags');
	
	if (div.innerHTML.indexOf('<i>none') == 0) {
		div.innerHTML = '';
	}
	
	text = text.replace(/<[^>]*>/ig, "");
	text = text.replace(/['"]+/ig, " ");
	//todo - split on comma so can enter multiple tags at once. 
	
	str = "<span class=\"tag\" id=\"tag"+text+"\">";
	str += "<input type=\"hidden\" name=\"tag_id[]\" id=\"tagi"+text+"\" value=\""+text+"\"/>";
	str += "<span>"+text+"</span>";
	str += "<a href=\"javascript:removeTag('"+text+"')\" class=\"delete\">X</a>";
	str += "</span>&nbsp; ";
	div.innerHTML = div.innerHTML + str;
	
	if (suggestion) {
		document.getElementById('suggestion'+suggestion).style.display='none';
	}
	return void('');
}
function removeTag(text) {
	if (document.getElementById("tag"+text)) {
		document.getElementById("tag"+text).style.textDecoration = "line-through";
		document.getElementById("tag"+text).style.fontSize = "0.6em";
	}
	if (document.getElementById("tagi"+text)) {
		document.getElementById("tagi"+text).value="-deleted-";
	}
}

</script>
<script src="http://www.google.com/jsapi"></script>
<script>
  // Load jQuery
  google.load("jquery", "1");


  function loadTagSuggestions(param) {
    $.getJSON("/portals/tags.ajax.php?"+param+"&callback=?",

      // on search completion, process the results
      function (data) {
	if (data) {
		var div = document.getElementById('suggestions');
		
		str = 'Suggestions: ';
		for(var tag_id in data) {
			var text = data[tag_id];
			
			text = text.replace(/<[^>]*>/ig, "");
			text = text.replace(/['"]+/ig, " ");
	
			str += "<span class=\"tag\" id=\"suggestion"+tag_id+"\">";
			str += "<span>"+text+"</span>";
			str += "<a href=\"javascript:addTag('"+text+"',"+tag_id+");\" class=\"use\">Use</a>";
			str += "</span>&nbsp; ";
		}

		div.innerHTML = str;
        }
        
      });
   }
   
   function checkDomain(that,portal_id) {
   	var v = that.value;
   	var ele = document.getElementById("checkMsg");
   	var btn = document.getElementById("submitButton");
   	btn.disabled = true;
   	if (v.length) {
   		if (v.match(/[A-Z]/)) {
   			v = v.toLowerCase();
   			that.value = v;
   		}
   		if (v.length < 4) {
   			ele.innerHTML = "Too short!";
   		} else if (v.indexOf('-') == 0) {
   			ele.innerHTML = "Can't start with '-'!";
   		} else if (v.indexOf('-') == v.length-1) {
   			ele.innerHTML = "Can't end with '-'!";
   		} else if (v.indexOf('--') >-1) {
   			ele.innerHTML = "Can't have consecutive '-'s!";
   		} else if (!v.match(/^([a-z].*[a-z0-9])$/)) { 
   			ele.innerHTML = "Must start with a letter, and end with letter or number!";
   		} else if (v.match(/^([a-z][a-z0-9-]+[a-z0-9])$/)) { 
   			ele.innerHTML = "checking...";
   			
   			$.getJSON("/portals/checkdomain.ajax.php?domain="+v+"&id="+portal_id+"&callback=?",
			
			      // on completion, process the results
			      function (data) {
				ele.innerHTML = data;
			        if (data.indexOf('available')>-1) {
			          btn.disabled = false;
			        }
    			      });
   			
   			
   			
   		} else {
   			ele.innerHTML = "Contains invalid charactors!";
   		}
   	} else {
   		ele.innerHTML = "no value specified!";
   	}
   }
   function initalPopulate(that,portal_id) {
   	if (that.value == '' && that.form.elements['title'].value.length>4) {
   	   that.value = that.form.elements['title'].value.toLowerCase().replace(/[^\w]+/g,'-');
   	   checkDomain(that,portal_id);
   	}
   }
   
</script>
<?

include($_SERVER['DOCUMENT_ROOT'].'/portals/footer.inc.php');
